package com.rh.bmw4s.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.rh.bmw4s.R;
import com.rh.bmw4s.adapter.CarAdapter;
import com.rh.bmw4s.bean.BaseBean;
import com.rh.bmw4s.bean.CarBean;
import com.rh.bmw4s.comm.ConfigValue;
import com.rh.bmw4s.comm.Constant;
import com.rh.bmw4s.utills.DealResult;
import com.rh.bmw4s.utills.DialogUtils;
import com.rh.bmw4s.utills.LogUtils;
import com.rh.bmw4s.utills.SPUtils;
import com.rh.bmw4s.utills.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 搜索结果界面
 */
public class SearchResultActivity extends BaseActivity {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.search_result_recy)
    LRecyclerView recyclerView;

    private View emptyView;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private CarAdapter mAdapter;
    private int type = 0;
    private int page = 0;
    private int count = 0;
    private int requestNum = 10;

    private int searchURL;  //搜索接口是哪个 1 全局搜索  2 二手车搜索 3新车  4 汽车用品  5汽车轮胎
    private String searchKey;  //搜索关键字
    private int cateId;  //二手车分类id
    private int anInt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);
        ButterKnife.bind(this);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            searchURL = bundle.getInt("searchUrl");
            searchKey = bundle.getString("searchKey");
            cateId = bundle.getInt("searchCarId");
        }
        anInt = SPUtils.getInstance().getInt(ConfigValue.userId);

        initRecy();
    }

    private void initRecy() {
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        emptyView = findViewById(R.id.empty_searchresult);

        recyclerView.setLayoutManager(new GridLayoutManager(SearchResultActivity.this, 2));
        //设置adapter，因为价格和角标显示不同，要分类显示
        switch (searchURL) {
            case 1://全局
                mAdapter = new CarAdapter(SearchResultActivity.this, 10);
                break;
            case 2://二手车
                mAdapter = new CarAdapter(SearchResultActivity.this, 0);
                break;
            case 3://新车
                mAdapter = new CarAdapter(SearchResultActivity.this, 1);
                break;
            case 4://汽车用品
                mAdapter = new CarAdapter(SearchResultActivity.this, 3);
                break;
            case 5://汽车轮胎
                mAdapter = new CarAdapter(SearchResultActivity.this, 4);
                break;
            default:
                mAdapter = new CarAdapter(SearchResultActivity.this, 10);
                break;
        }


        mAdapter.setDataList(new ArrayList<CarBean>());
        lRecyclerViewAdapter = new LRecyclerViewAdapter(mAdapter);
        recyclerView.setAdapter(lRecyclerViewAdapter);
        GridItemDecoration divider = new GridItemDecoration.Builder(SearchResultActivity.this)
                .setHorizontal(R.dimen.size_10dp)
                //.setVertical(R.dimen.size_10dp)
                .setColorResource(R.color.app_bg1)
                .build();
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(divider);

        //设置头部加载颜色  刷新图标颜色  字体颜色  背景颜色
        recyclerView.setHeaderViewColor(R.color.white, R.color.white, R.color.app_bg1);
        //设置底部加载颜色
        recyclerView.setFooterViewColor(R.color.white, R.color.white, R.color.app_bg1);
        //设置底部加载文字提示
        recyclerView.setFooterViewHint("努力加载中", "已经全部加载", "网络不给力啊");

        recyclerView.setLoadMoreEnabled(true);
        recyclerView.setPullRefreshEnabled(false);

        recyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (count < ((page + 1) * requestNum)) {
                    recyclerView.setNoMore(true);
                } else {
                    page++;
                    getDatas();
                }
            }
        });
        getDatas();
        DialogUtils.showProgressDlg(SearchResultActivity.this, "努力加载中......");

        //点击item跳转详情
        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (mAdapter.getDataList().size() > position) {
                    CarBean carBean = mAdapter.getDataList().get(position);
                    Intent intent = new Intent(SearchResultActivity.this, WebShowActivity.class);
                    intent.putExtra("url", Constant.H5DETAILS + carBean.getId() + "/mem_id/" + anInt);

//                    if (searchURL == 4 || searchURL == 5) {
//                        //轮胎和汽车用品详情页
//                        intent.putExtra("url", "http://4s.liexianghudong.com/index.php/home/index/qixiang/id/" + carBean.getId() + "/mem_id/" + anInt);
//                    } else {
//                        //二手车详情页
//                        intent.putExtra("url", "http://4s.liexianghudong.com/index.php/home/index/ershouxiang/id/" + carBean.getId() + "/mem_id/" + anInt);
//                    }
                    SearchResultActivity.this.startActivity(intent);
                }
            }

        });

    }

    PostRequest<String> request = null;

    private void getDatas() {
        recyclerView.setVisibility(View.VISIBLE);
        emptyView.setVisibility(View.GONE);

        switch (searchURL) {
            case 1:
                tvMiddleTitle.setText("全局搜索");
                request = OkGo.<String>post(Constant.SearchAll);
                break;
            case 2:
                tvMiddleTitle.setText("二手车搜索");
                request = OkGo.<String>post(Constant.SearchOldCar)
                        .params("cat_id", cateId);
                break;
            case 3:
                tvMiddleTitle.setText("新车搜索");
                request = OkGo.<String>post(Constant.SearchNewCar);
                break;
            case 4:
                tvMiddleTitle.setText("汽车用品搜索");
                request = OkGo.<String>post(Constant.SearchYongPin);
                break;
            case 5:
                tvMiddleTitle.setText("汽车轮胎搜索");
                request = OkGo.<String>post(Constant.SearchLunTai);
                break;
            default:
                tvMiddleTitle.setText("全局搜索");
                request = OkGo.<String>post(Constant.SearchAll);
                break;
        }

        request.tag(this)
                .params("key", searchKey)
                .params("page", page)
                .params("count", requestNum)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        LogUtils.d("aaa", "page:" + page + "  count:" + requestNum + "  key:" + searchKey + "catid:" + cateId);
                        LogUtils.d("aaa", response.body().toString());

                        BaseBean<CarBean> bean = DealResult.getInstace().dealData(SearchResultActivity.this, response, new TypeToken<BaseBean<CarBean>>() {
                        }.getType());
                        if (page == 0 && bean.getDatas().size() == 0) {
                            recyclerView.setVisibility(View.GONE);
                            emptyView.setVisibility(View.VISIBLE);
                            return;
                        }
                        List<CarBean> beans = bean.getDatas();
                        mAdapter.addAll(beans);
                        count = mAdapter.getItemCount();
                        recyclerView.refreshComplete(requestNum);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(SearchResultActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    @OnClick(R.id.title_left_one_btn)
    public void onViewClicked() {
        finish();
    }
}
